<?php

namespace App\Module\Sub;

use App\depository\ManageMapExtraDep;
use App\depository\SystemDep;
use App\Enum\MapEnum;
use App\Module\BaseModule;
use App\depository\ManageMapDep;
use App\Service\DictService;

class SubMapModule extends BaseModule
{

    public function init($request)
    {
        $dictService = new DictService();

        $dictService->setMapJson();

        $data['dict'] = $dictService->getDict();

        return self::response($data);
    }



    public function edit($request)
    {
        $param = $request->input();
        $teamId = $request->headers->get('TeamId');

        $mapExtraDep = new ManageMapExtraDep();

        $resExtra = $mapExtraDep->firstByTeamIdMapId($teamId,$param['map_id']);
        if (!$resExtra) {
            $data = [
                'extra' => $param['extra'],
                'manage_map_id' => $param['map_id'],
                'gh_id' => $teamId,
                'status' => MapEnum::EXTRA_OK
            ];
            $mapExtraDep->add($data);
        }else{
            $data = [
                'extra' => $param['extra'],
            ];
            $mapExtraDep->upd($resExtra->id,$data);
        }

        return self::response();

    }

    public function list($request)
    {
        $param = $request->input();

        $teamId = $request->headers->get('TeamId');

        $mapDep = new ManageMapDep();
        $resList = $mapDep->list($param);
        $list = $resList->getCollection()->toBase();
        $extraDep = new ManageMapExtraDep();
        $resExtras = $extraDep->getByMapIds($teamId,$list->pluck('id'));

        $data['list'] = $list->map(function ($item) use ($resExtras) {
            $resExtra = $resExtras->first((function($item1) use ($item){
                return $item1->manage_map_id == $item->id;
            }));
            return [
                'map_id' => $item->id,
                'map_name' => $item->map_name,
                'zh_name' => $item->zh_name,
                'extra' => $resExtra ? $resExtra->extra :  "",
            ];
        });

        $data['page'] = [
            'per_page' => $param['per_page'],
            'current_page' => $param['current_page'],
            'total_page' => $resList->lastPage(),
            'total' => $resList->total(),
        ];

        return self::response($data);
    }

}

